package com.clkj.sunhelp.mvp.jobdeal.jobwaittododetail;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import android.widget.Toast;

import com.clkj.sunhelp.R;
import com.clkj.sunhelp.adapter.rv.RecycleViewOfChoosedPicAdapter;
import com.clkj.sunhelp.app.CustomApplication;
import com.clkj.sunhelp.bean.JobDetail;
import com.clkj.sunhelp.bean.JobWaitToDoItem;
import com.clkj.sunhelp.common.IntentKey;
import com.clkj.sunhelp.mvp.base.BaseActivity;
import com.clkj.sunhelp.mvp.jobdeal.jobwaittododetail.choosephotoandupdate.ActivityChoosePicAndUpdate;
import com.clkj.sunhelp.util.ImageCompressUtil;
import com.clkj.sunhelp.util.LogUtil;
import com.clkj.sunhelp.util.ToastUtil;
import com.clkj.sunhelp.util.schedulers.SchedulerProvider;
import com.jakewharton.rxbinding.view.RxView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 待办事项详情
 * Created by Administrator on 2017/3/28.
 */

public class ActivityJobWaitToDoDetail extends BaseActivity implements JobWaitToDoDetailContract.View {

    private RecyclerView rvPics;
    //private TextView tvChoosePic;

    private TextView tvChoosePicAndUpdate;
    //private TextView tvApplicatemanInfo;
    private TextView tvApplicatePerson;


    private TextView tvCurProcess;
    private TextView tvHuzhuName;
    private TextView tvHuizhuSex;
    private TextView tvBrithInfo;
    private TextView tvIdCardNo;
    private TextView tvHujiAddress;
    private TextView tvJuzhuAddress;
    private TextView tvFamilypersonNum;
    private TextView tvBaozhangpersonNum;
    private TextView tvContactTel;
    private TextView tvHouseKind;
    private TextView tvHouseXingzhi;
    private TextView tvHouseNum;
    private TextView tvFamilyCaichanInfo;
    private TextView tvApplyDibaoReason;

    private TextView tvUploadPic;

    private final int REQUEST_CODE_CAMERA = 1000;
    private final int REQUEST_CODE_GALLERY = 1001;


    RecycleViewOfChoosedPicAdapter mPicChoosedAdapter;
    private List<PhotoInfo> mPhotoList = new ArrayList<>();
    private List<File> fileList = new ArrayList<>();


    JobWaitToDoItem mJobWaitToDoItem;

    JobWaitToDoDetailContract.Presenter mPresenter;


    JobDetail mJobDetail;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_job_wait_to_do_detail);

        initData();
        assignView();
        initView();
        mPresenter = new JobWaitToDoDetailPresenter(this, SchedulerProvider.getInstance(), CustomApplication.getInstance().getHttpService());
        getJobDetail();
    }

    @Override
    public void initData() {

        mJobWaitToDoItem = (JobWaitToDoItem) getIntent().getSerializableExtra(IntentKey.INTENT_KEY_JOB_ITEM);

    }

    @Override
    public void assignView() {


        //rvPics = (RecyclerView) findViewById(R.id.rv_pics);
        tvChoosePicAndUpdate = (TextView) findViewById(R.id.tv_choose_pic_and_update);
        //tvUploadPic = (TextView) findViewById(R.id.tv_upload_pic);

        //tvApplicatemanInfo = (TextView) findViewById(R.id.tv_applicateman_info);

        tvApplicatePerson = (TextView) findViewById(R.id.tv_applicate_person);

        tvCurProcess = (TextView) findViewById(R.id.tv_cur_process);
        tvHuzhuName = (TextView) findViewById(R.id.tv_huzhu_name);
        tvHuizhuSex = (TextView) findViewById(R.id.tv_huizhu_sex);

        tvBrithInfo = (TextView) findViewById(R.id.tv_brith_info);
        tvIdCardNo = (TextView) findViewById(R.id.tv_id_card_no);
        tvHujiAddress = (TextView) findViewById(R.id.tv_huji_address);
        tvJuzhuAddress = (TextView) findViewById(R.id.tv_juzhu_address);
        tvFamilypersonNum = (TextView) findViewById(R.id.tv_familyperson_num);
        tvBaozhangpersonNum = (TextView) findViewById(R.id.tv_baozhangperson_num);
        tvContactTel = (TextView) findViewById(R.id.tv_contact_tel);
        tvHouseKind = (TextView) findViewById(R.id.tv_house_kind);
        tvHouseXingzhi = (TextView) findViewById(R.id.tv_house_xingzhi);
        tvHouseNum = (TextView) findViewById(R.id.tv_house_num);
        tvFamilyCaichanInfo = (TextView) findViewById(R.id.tv_family_caichan_info);
        tvApplyDibaoReason = (TextView) findViewById(R.id.tv_apply_dibao_reason);

    }

    @Override
    public void initView() {

        initTitleWithRightTvOrIv(null, null, mJobWaitToDoItem.getSchemename(), true, null, null);

       /* GridLayoutManager mLayoutManager =  new GridLayoutManager(this,2);
        rvPics.setLayoutManager(mLayoutManager);
        //rvPics.addItemDecoration(new DividerGridItemDecoration(this));
        mPicChoosedAdapter = new RecycleViewOfChoosedPicAdapter(mPhotoList,this);
        //mPicChoosedAdapter.setPicItemClickListener(new PicItemClickListenerImpl());
        rvPics.setAdapter(mPicChoosedAdapter);*/


        RxView.clicks(tvChoosePicAndUpdate)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Intent toChoosePicAndUpdate = new Intent(ActivityJobWaitToDoDetail.this, ActivityChoosePicAndUpdate.class);
                        toChoosePicAndUpdate.putExtra(IntentKey.INTENT_KEY_JOB_ITEM,mJobWaitToDoItem);
                        startActivity(toChoosePicAndUpdate);
                    }
                });

        /*RxView.clicks(tvChoosePic)
                .subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                final FunctionConfig functionConfig = initGalleyFunctionConfig();

                NewActionSheet.createBuilder(ActivityJobWaitToDoDetail.this, getSupportFragmentManager())
                        .setCancelButtonTitle("取消")
                        .setOtherButtonTitles("打开相册", "拍照")
                        .setCancelableOnTouchOutside(true)
                        .setListener(new NewActionSheet.ActionSheetListener() {
                            @Override
                            public void onDismiss(NewActionSheet actionSheet, boolean isCancel) {

                            }

                            @Override
                            public void onOtherButtonClick(NewActionSheet actionSheet, int index) {
                                switch (index) {
                                    case 0:
                                        final FunctionConfig functionConfig = initGalleyFunctionConfig();
                                        GalleryFinal.openGalleryMuti(REQUEST_CODE_GALLERY, functionConfig, mOnHanlderResultCallback);

                                        break;
                                    case 1:
                                        final FunctionConfig functionConfigNew = initGalleyFunctionConfig();

                                        if (mPhotoList.size()<Config.UPLOAD_PIC_NUM_PER_TIME)
                                        {
                                            GalleryFinal.openCamera(REQUEST_CODE_CAMERA, functionConfigNew, mOnHanlderResultCallback);
                                        }else{
                                            ToastUtil.showShort(ActivityJobWaitToDoDetail.this, "最多上传"+ Config.UPLOAD_PIC_NUM_PER_TIME+"张图片");
                                        }


                                        break;

                                    default:
                                        break;
                                }
                            }
                        })
                        .show();
            }
        });*/


        /*RxView.clicks(tvUploadPic)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (mPhotoList.size()>0)
                        {
                            compressedPicAndUpload(mPhotoList);
                        }else {
                            ToastUtil.showShort(ActivityJobWaitToDoDetail.this,"请选择要提交的图片");
                        }
                    }
                });*/
    }

    @Override
    public void getJobDetail() {
        mPresenter.getJobDetail(mJobWaitToDoItem.getId());
    }

    @Override
    public void onGetJobDetailSuccess(JobDetail jobDetail ) {
        mJobDetail = jobDetail;
        //tvApplicatemanInfo .setText("申请人"+mJobWaitToDoItem.getHZName()+"的"+mJobWaitToDoItem.getSchemename()+"申请");
        tvApplicatePerson.setText(mJobWaitToDoItem.getHZName());
        tvCurProcess.setText(mJobWaitToDoItem.getActivityName());
        tvHuzhuName.setText(mJobDetail.getHZNAME());
        tvHuizhuSex.setText(mJobDetail.getSEX());

        tvBrithInfo.setText(mJobDetail.getCSNY());
        tvIdCardNo.setText(mJobDetail.getSFZH());
        tvHujiAddress.setText(mJobDetail.getHJD());
        tvJuzhuAddress .setText(mJobDetail.getHJD());
        tvFamilypersonNum.setText(String.valueOf(mJobDetail.getJTRKS()));
        tvBaozhangpersonNum .setText(String.valueOf(mJobDetail.getBZRKS()));
        tvContactTel .setText(mJobDetail.getLXDH());
        tvHouseKind.setText(mJobDetail.getZFLX());
        tvHouseXingzhi.setText(mJobDetail.getZFXZ());
        tvHouseNum.setText(mJobDetail.getZFTS());
        tvFamilyCaichanInfo.setText(mJobDetail.getJTCCQK());
        tvApplyDibaoReason.setText(mJobDetail.getSQJZYY());

    }

    @Override
    public void onGetJobDetailError(String tip) {
        ToastUtil.showShort(this,tip);
    }



    @Override
    public void setPresenter(JobWaitToDoDetailContract.Presenter presenter) {

    }

    @Override
    public void showLoading() {
        showProgressDialog(false, null);
    }

    @Override
    public void dismissLoading() {
        dismissProgressDialog();
    }

    //初始化图片选择functionconfig
    private FunctionConfig initGalleyFunctionConfig()
    {
        FunctionConfig.Builder functionConfigBuilder = new FunctionConfig.Builder();
        functionConfigBuilder.setMutiSelectMaxSize(5);
        functionConfigBuilder.setEnableCamera(true);
        functionConfigBuilder.setEnablePreview(true);
        functionConfigBuilder.setSelected(mPhotoList);//添加过滤集合
        return functionConfigBuilder.build();
    }

    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int requestCode, List<PhotoInfo> resultList) {



            if (requestCode == REQUEST_CODE_GALLERY)
            {
                if (resultList != null) {
                    mPhotoList.clear();
                    mPhotoList.addAll(resultList);
                    mPicChoosedAdapter.notifyDataSetChanged();
                }
            }
            //如果是拍照的话，则直接添加
            if (requestCode == REQUEST_CODE_CAMERA)
            {
                if (resultList != null) {
                    mPhotoList.addAll(resultList);
                    mPicChoosedAdapter.notifyDataSetChanged();
                }
            }

        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            Toast.makeText(ActivityJobWaitToDoDetail.this, errorMsg, Toast.LENGTH_SHORT).show();
        }
    };

    private static final int HANDLER_TAG_COMPRESSED_PIC_SUCCESS = 1000;

    //处理图片压缩的handler
    Handler mCompressedFileHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case HANDLER_TAG_COMPRESSED_PIC_SUCCESS:

                    List<File> compressedPicList = (List<File>) msg.obj;
                    //uploadPic(compressedPicList);

                    break;
            }
        }
    };



    //压缩图片并且上传
    private void compressedPicAndUpload(final List<PhotoInfo> choosedPhotoInfo){

        showProgressDialog(false,null);

        final List<File> compressedFileList = new ArrayList<>();



        Observable.from(choosedPhotoInfo)

                .map(new Func1<PhotoInfo, File>() {
                    @Override
                    public File call(PhotoInfo photoInfo) {
                        LogUtil.e("BeforeCompressFileSize:"+new File(photoInfo.getPhotoPath()).length() / 1024 + "k");

                        return ImageCompressUtil.compressLocalPic(photoInfo.getPhotoPath());
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<File>() {
                    @Override
                    public void call(File file) {
                        LogUtil.e("afterCompressFileSize:"+file.length() / 1024 + "k");

                        compressedFileList.add(file);

                        if (compressedFileList.size() == choosedPhotoInfo.size())
                        {
                            Message message = new Message();
                            message.what = HANDLER_TAG_COMPRESSED_PIC_SUCCESS;
                            message.obj = compressedFileList;
                            mCompressedFileHandler.sendMessage(message);
                        }
                    }
                });
    }





}
